package bainuo

import groovy.sql.Sql


def execute() {
    def conn
    try {
        conn = groovy.sql.Sql.newInstance(mypara.hqcon(2))
        String sql = '''SELECT
        CAST(b.crowno AS VARCHAR) + '$' + p.vbillcode AS crowno_vbillcode
            FROM
                po_praybill p
                    INNER JOIN
                po_praybill_b b ON p.pk_praybill = b.pk_praybill
            '''
        def it = conn.rows(sql)

        processDataInBatches(it, 500);
    } catch (Exception e) {
        e.printStackTrace()
        return ["state": 0, "Ascript": "查询错误: ${e.message}", "data": false]
    } finally {
        if (conn != null) {
            conn.close()
        }
    }
}

// 按批次处理数据
def processDataInBatches(def data, int batchSize) {
    for (int i = 0; i < data.size(); i += batchSize) {
        List<String> batch = data.subList(i, Math.min(i + batchSize, data.size()));
        processBatch(batch);
    }
}

def processBatch(def it){
    List<Map<String,String>> items = new ArrayList<>();
    for (def its: it) {
        if (its!= null){
            Map<String,String> item = new HashMap<>();
            item.put("crowno_vbillcode", its.crowno_vbillcode);
            items.add(item);
        }
    }
    Map<String,List> pushData = new HashMap<>()
    pushData.put("items", items);
    push(pushData)
}

def push(data) {
    println "-------------------------任务启动-------------------------"
    try {
        def items = data.get("items")

        for (def item : items) {
            def params = [:]
            params.put("erp_bill_code_no", item.get("crowno_vbillcode"))

            // 更新为调用 checkErpBillCodeAndGetFileId
            def result = checkErpBillCodeAndGetFileId(params)
            if (result.exists) {
                println "Found file_id: ${result.file_id}"
            } else {
                println "No matching record or file_id found."
            }
        }
        println "-------------------------传输完成-------------------------"
    } catch (Exception e) {
        e.printStackTrace();
        return ["state": 0, "Ascript": "请求参数错误,请检查"]
    }
}

static def checkErpBillCodeAndGetFileId(params) {
    def conn = null
    try {
        conn = Sql.newInstance("jdbc:mysql://10.1.1.209:3306/cpu_sourcing", "oper_dc", "operzADF2020qwer", "com.mysql.cj.jdbc.Driver")
        String erpBillCodeNo = params.get("erp_bill_code_no")
        String sqlStatement = "SELECT file_id FROM ipu_pu_req WHERE erp_bill_code_no = ? LIMIT 1"
        def result = conn.firstRow(sqlStatement, [erpBillCodeNo])

        if (result != null && result.file_id != null) {
            return ["exists": true, "file_id": result.file_id]
        } else {
            return ["exists": false, "file_id": null]
        }
    } catch (Exception e) {
        e.printStackTrace()
        return ["exists": false, "file_id": null, "error": e.message]
    } finally {
        if (conn != null) {
            conn.close()
        }
    }
}